const express = require('express');
const router = express.Router();
const query = require("../util/db.js")
const R = require("../util/resultJson.js")

router.get("/",function (req,res) {
    res.render("store/store-list")
})

router.get("/edit",function (req,res) {
    res.render("store/store-edit")
});

router.get("/info/:id",function (req,res) {
    let sql = "select * from store where id = ?";
    query(sql,[req.params.id]).then(list=>{
        if(list.length > 0){
            res.json(R.success(list[0]));
        }else {
            res.json(R.error("编号异常！"))
        }
    })
})

router.get("/page",function (req,res) {
    const {page,limit,name,status} = req.query;
    let sql = "select * from store where 1 = 1 ";
    let objs = [];
    if(name){
        sql+="and name like ? ";
        objs.push("%"+name+"%");
    }
    if(status){
        sql+="and status = ? ";
        objs.push(status)
    }
    query(sql,objs).then(list=>{
        const count = list.length;
        sql+="order by id desc limit ?,?";
        objs.push((page-1)*limit);
        objs.push(parseInt(limit));
        query(sql,objs).then(data=>{
            res.json(R.page(count,data));
        })
    })
})

router.post("/update",function (req,res) {
    const store = req.body;
    if(store.id){
        let sql = "update store set name = ?,address = ?,remake = ?,status = ? where id = ?";
        query(sql,[store.name,store.address,store.remake,store.status,store.id]).then(r=>{
            res.json(R.success());
        })
    }else{
        let sql = "select * from store where name = ?";
        query(sql,[store.name]).then(list=>{
            if(list.length>0){
                res.json(R.error("仓库名已存在！"));
            }else{
                sql = "insert into store values(null,?,?,?,?)";
                query(sql,[store.name,store.address,store.remake,store.status]).then(r=>{
                    res.json(R.success());
                })
            }
        })
    }
})

router.delete("/delete/:id",function (req,res) {
    let sql = "select * from goods_store where store_id = ?";
    query(sql,[req.params.id]).then(list=>{
        if(list.length>0){
            res.json(R.error("该仓库已被使用，禁止删除！"));
        }else{
            sql = "delete from store where id = ?";
            query(sql,[req.params.id]).then(r=>{
                res.json(R.success())
            })
        }
    })
})

router.post("/status",function (req,res) {
    let sql = "update store set status = ? where id = ?";
    query(sql,[req.body.status,req.body.id]).then(r=>{
        res.json(R.success())
    })
})

router.get("/select",function (req,res) {
    let sql = "select * from store order by id desc ";
    query(sql).then(list=>{
        res.json(R.success(list));
    })
})

module.exports = router;
